package it.enricod.jcontextfree.gui.controllers.impl;

import it.enricod.jcontextfree.engine.samples.IProgramCatalogEntry;
import it.enricod.jcontextfree.gui.IMainFrame;
import it.enricod.jcontextfree.gui.controllers.IMainController;
import it.enricod.jcontextfree.gui.events.DrawProgramEvent;
import it.enricod.jcontextfree.gui.events.LoadProgramCommandEvent;
import it.enricod.jcontextfree.model.IProgramPM;
import it.enricod.jcontextfree.model.IProgramsRegistry;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.bushe.swing.event.EventBus;
import org.bushe.swing.event.EventServiceEvent;
import org.bushe.swing.event.EventSubscriber;
import org.jdesktop.swingworker.SwingWorker;

import com.google.inject.Inject;

public class MainController implements IMainController, EventSubscriber<EventServiceEvent> {

	private Logger logger = Logger.getLogger("MainController");
	private IMainFrame mainFrame;
	// private IProgramLoader programLoader;
	private IProgramsRegistry programsRegistry;

	@Inject
	public MainController(IMainFrame mainFrame, IProgramsRegistry programsRegistry) {
		this.mainFrame = mainFrame;
		this.programsRegistry = programsRegistry;

		EventBus.subscribeStrongly(LoadProgramCommandEvent.class, this);
		EventBus.subscribeStrongly(DrawProgramEvent.class, this);
		initGui();
	}

	private void initGui() {
		IProgramPM welcomeProgram = programsRegistry.getWelcomProgram();
		mainFrame.getProgramsTabbedPane().addProgramTab(welcomeProgram);
	}

	// @Inject
	// public void setProgramLoader(IProgramLoader programLoader) {
	// this.programLoader = programLoader;
	// }

	public void startGui() {
		mainFrame.setVisible(true);
	}

	public void onEvent(EventServiceEvent arg0) {
		if (arg0 instanceof LoadProgramCommandEvent) {
			logger.debug("Ricevuto evento LoadProgramCommandEvent");
			AProgramLoader loader = new AProgramLoader();
			loader.execute();
		} else if (arg0 instanceof DrawProgramEvent) {
			logger.debug("Ricevuto evento DrawProgramEvent");
			DrawProgramEvent evn = (DrawProgramEvent) arg0;
			drawProgram((String) evn.getSource());
		}
	}

	private void drawProgram(String programAsText) {
		// IProgramsTabbedPane drawPanel = mainFrame.getProgramsTabbedPane();
		// IProgram program = programLoader.load(programAsText);
		// drawPanel.drawProgram(program);
	}

	class AProgramLoader extends SwingWorker<Object, Object> {

		public Object doInBackground() {
			IProgramCatalogEntry programCatalogEntry = mainFrame.getProgramsCatalog().getEntry("DEMO4");
			mainFrame.getProgramPanel().setProgramAsText(programCatalogEntry.getProgramAsText());
			return null;
		}

		@Override
		protected void done() {
			try {
				logger.debug("loading finished");
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
}
